<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Equipment Config</title>
	<link rel="stylesheet" href="../js/easyui/themes/bootstrap/easyui.css">
	<link rel="stylesheet" href="../js/easyui/themes/icon.css">
	<link rel="stylesheet" href="../js/easyui/themes/color.css">
	<link rel="stylesheet" href="../css/index-ui.css" />
	<script type="text/javascript" src="../js/easyui/jquery.min.js"></script>
	<script type="text/javascript" src="../js/easyui/jquery.easyui.min.js"></script>
	<script type="text/javascript" src="../js/echarts.min.js"></script>
	<script type="text/javascript" src="../js/ams.util.js"></script>
	<script type="text/javascript" src="../js/webapi.js"></script>
</head>
<body onload="on_page_init()">
	<div id="div_data_toolbar" style="padding:5px;padding-left:1px;padding-right:100px">
		<div style="float:right;padding-left:30px">
			<a class="easyui-linkbutton" style="width:100px" iconCls="icon-reload" onclick="on_page_init()">Refresh</a>
			<a class="easyui-linkbutton" style="width:100px" iconCls="icon-more" onclick="on_settings()">Settings</a>
			<a class="easyui-linkbutton" style="width:100px" iconCls="icon-chart" onclick="on_chart_view()">Chart</a>
		</div>
	</div>
	<br/><br/>
	<div style="height:90%;padding-left:100px;padding-right:100px">
		<table id="eq_data_grid" class="easyui-datagrid" style="width:100%;height:100%">
			<thead>
				<tr>
					<th data-options="field:'ck',checkbox:true"></th>
					<th data-options="field:'name',width:170">Name</th>
					<th data-options="field:'cv',width:140">Current Value</th>
					<th data-options="field:'type',width:400">Type</th>
				</tr>
			</thead>
		</table>
	</div>

	<div id="window_data_chart" class="easyui-window" title="Realtime Data Chart"
		data-options="modal:true,closed:true,iconCls:'icon-help',cls:'c1'" style="width:850px;height:600px;padding:10px;">
		<div id="chart_container" style="height: 60%"></div>
	</div>

	<div id="window_setting" class="easyui-window" title="Data Monitor Setting"
		data-options="modal:true,closed:true,iconCls:'icon-help',cls:'c1'" style="width:450px;height:400px;padding:10px;">
		<div style="float:right;padding-bottom:5px">
				<a class="easyui-linkbutton" style="width:100px" iconCls="icon-undo" onclick="on_setting_restore()">Restore</a>
				<a class="easyui-linkbutton" style="width:100px" iconCls="icon-ok" onclick="on_setting_apply()">Apply</a>
		</div>
		<table id="eq_data_item_select_grid" class="easyui-datagrid" style="width:100%;height:90%">
			<thead>
				<tr>
					<th data-options="field:'ck',checkbox:true"></th>
					<th data-options="field:'name',width:350">Name</th>
					<th data-options="field:'unit',width:150,hidden:true">Description</th>
				</tr>
			</thead>
		</table>
	</div>
	
</body>

<script language="javascript"> 

var g_dyn_chart = null
var g_dyn_chart_update_timer = 0
var g_chart_series = null
var ONE_SECOND = 1000
var rnd_value = Math.random() * 1000
var PT_COUNT = 200
var t_now = new Date()
var eqn = null

function on_page_init()
{
	eqn = get_page_param('eq')
	// get monitor data list from server
	$('#eq_data_grid').datagrid({
		rownumbers:'true',
		lines:true,
		clickToEdit: false,
		dblclickToEdit: false,
		loadMsg: 'Loading Data ......',
		method:'get'
	})

	if (ams_is_sim_mode()) {
		$('#eq_data_grid').datagrid({
			url: 'data_item_monitor_01.json'
		})
	} else {
		// TODO: getVarSelect
		on_refesh_view();
	}
}

function on_refesh_view()
{
	$.ajax({
	type: 'POST',
	contentType: 'application/json',
	url: getWebServiceUrl("getVarSelect"),
	data:JSON.stringify({
		"eqName":eqn
	}),
	dataType: 'json',
	success: function (json_data) {
		if(json_data.d!=""){
			console.log(JSON.parse(json_data.d))
			$('#eq_data_grid').datagrid({
				data:JSON.parse(json_data.d)
			})
		}
		else{
			$('#eq_data_grid').datagrid('loadData', { total: 0, rows: [] });
		}
	},
	error: function (response) {
		//alert(errorThrown.message);
		//alert('Error: ' + response.responseText)
		$.messager.alert("Error", "Error: " + response.responseText, "error");
	}
});
}

function on_chart_view()
{
	var rows = $('#eq_data_grid').datagrid('getSelections')
	if (rows.length == 0) {
		//alert('Select at least one data item please.')
		$.messager.alert("Tips", "Select at least one data item please.", "info");
		return
	} else if (rows.length > 8) {
		//alert('Chart can display 8 series at most.')
		$.messager.alert("Tips", "Chart can display 8 series at most.", "info");
		return
	}

	for(var i=0;i<rows.length;i++){
		if(rows[i].type=='STRING'){
			//alert('It can\'t be String type.')
			$.messager.alert("Tips", "It can\'t be String type.", "info");
			return
		}
	}

	$('#window_data_chart').window({
		onOpen:function(){
			chart_init()
		},
		onClose:function(){
			clearInterval(g_dyn_chart_update_timer)
			g_dyn_chart.clear()
			g_dyn_chart.dispose()
			g_dyn_chart = null
		}
	})
	$('#window_data_chart').window('open')
}

function on_setting_apply()
{	
	var rows = $('#eq_data_item_select_grid').datagrid('getSelections')
	//if (rows.length == 0) {
		//alert('Select at least one data item please.')
		//$.messager.alert("Tips", "Select at least one data item please.", "info");
		//return
	//}
	if (rows.length > 6){
		$.messager.alert("Tips", "Only 6 data items can be selected at most.", "info");
		return
	}
	var selNames = new Array();
	for(var i =0;i<rows.length;i++){
		selNames.push(rows[i].name)
	}
	if (ams_is_sim_mode()) {
		//alert("Save success")
		$.messager.alert("Tips", "Save success.", "info");
	} else {
		// TODO: getVarSelect
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("setVarSelect"),
			data:JSON.stringify({
				"eqName":eqn,
				"selNames":selNames
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				//alert("Save success")
				$.messager.alert("Tips", "Save success.", "info");
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
		on_refesh_view();
	}
}

function on_setting_restore()
{
	$('#eq_data_item_select_grid').datagrid('clearSelections')
}

function on_settings()
{
	$('#window_setting').window('open')
	load_data_item_setting()
}

function get_selected_data_item()
{
	var rows = $('#eq_data_grid').datagrid('getSelections')
	return rows
}

function load_data_item_setting()
{
	var query_url = ''
	$('#eq_data_item_select_grid').datagrid({
		rownumbers:'true',
		lines:true,
		clickToEdit: false,
		dblclickToEdit: false,
		loadMsg: 'Loading Data ......',
		method:'get'
	})
	var selectedItems=[]
	if (ams_is_sim_mode()) {
		query_url = 'data_item_all_01.json'
		$('#eq_data_item_select_grid').datagrid({
			url: query_url
		})
		$.getJSON('data_item_monitor_01.json', function(json_data) {
			$.getJSON('data_item_all_01.json', function(json_data2) {
				for(var i=0;i<json_data.total;i++){
					for(var k=0;k<json_data2.total;k++){
						if(json_data.rows[i].name==json_data2.rows[k].name){
							$('#eq_data_item_select_grid').datagrid('selectRow',k)
							break
						}
					}
				}
			})
		})
	} else {
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("GetEquipAllVarList"),
			data:JSON.stringify({
				"equipId":eqn
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				$('#eq_data_item_select_grid').datagrid({
					data: JSON.parse(json_data.d)
				})
				$.ajax({
					type: 'POST',
					contentType: 'application/json',
					url: getWebServiceUrl("getVarSelect"),
					data:JSON.stringify({
						"eqName":eqn
					}),
					dataType: 'json',
					success: function (json_data2) {
						if(json_data2.d != ''){
							console.log(JSON.parse(json_data2.d))
							for(var i=0;i<JSON.parse(json_data2.d).total;i++){
								for(var k=0;k<JSON.parse(json_data.d).total;k++){
									if(JSON.parse(json_data2.d).rows[i].name==JSON.parse(json_data.d).rows[k].name){
										$('#eq_data_item_select_grid').datagrid('selectRow',k)
										break
									}
								}
							}
						}
						
					},
					error: function (response) {
						//alert(errorThrown.message);
						//alert('Error: ' + response.responseText)
						$.messager.alert("Error", "Error: " + response.responseText, "error");
					}
				});
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function chart_init()
{
	if (g_dyn_chart == null) {
	//	alert('get chart obj')
		var dom = document.getElementById("chart_container")
		g_dyn_chart = echarts.init(dom)
	}

	g_dyn_chart.clear()

//	console.log(myChart)
//	var app = {}
	option = {
		title: {
			text: 'Realtime Data'
		},
		/*
		tooltip: {
			trigger: 'axis',
			formatter: function (params) {
				params = params[0];
				var date = new Date(params.name);
				return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1];
			},
			axisPointer: {
				animation: false
			}
		},
		*/
		xAxis: {
			type: 'time',
		//	timeFormat: 'second',
			splitLine: {
				show: true
			}
		},
		yAxis: {
			type: 'value',
			boundaryGap: [0, '100%'],
			splitLine: {
				show: true
			}
		},
		legend: {
			orient: 'horizontal', // 'vertical'
			x: 'right', // 'center' | 'left' | {number},
			y: 'top', // 'center' | 'bottom' | {number}
			backgroundColor: '#eee',
        //	borderColor: '#eee',
        	borderWidth: 1,
        	padding: 10,    // [5, 10, 15, 20]
        	itemGap: 20,
		}
	}

	g_dyn_chart.setOption(option, true)

	// get selected data items
	var data_sel_array = get_selected_data_item()
	chart_create_series(/*tag_name_array*/data_sel_array)
//	console.log(data_sel_array)

	chart_load_hist_data()

	// console.log(g_chart_series)
	g_dyn_chart.setOption(g_chart_series)
	g_dyn_chart_update_timer = setInterval("chart_get_and_add_new_data()", 3000)
}

function chart_create_series(tag_name_array)
{
//	console.log(tag_name_array)
	g_chart_series = {}
	g_chart_series['series'] = []
	for (var i = 0; i < tag_name_array.length; i++) {
		var tn = tag_name_array[i].name
		var __serie = {}
		__serie['name'] = tn
		__serie['type'] = 'line'
		__serie['showSymbol'] = false
		__serie['hoverAnimation'] = false
		var __data = []
		__serie['data'] = __data

		g_chart_series['series'].push(__serie)
	}
}

function chart_load_hist_data()
{
	if (g_chart_series == null) {
		//alert('null g_chart_series')
		$.messager.alert("Tips", "null g_chart_series.", "info");
		return
	}

	var data_sel_array = get_selected_data_item()
	var selNames = new Array();
	for(var i =0;i<data_sel_array.length;i++){
		selNames.push(data_sel_array[i].name)
	}
	if (ams_is_sim_mode()) {
		for (var i = 0; i < g_chart_series['series'].length; i++) {
			var __data = g_chart_series['series'][i].data
			var __name = g_chart_series['series'][i].name
			__sim_gen_hist_data(null,__data,__name)
		}
	}else{
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getEquipVarHistDatas"),
			data:JSON.stringify({
				"eqName":eqn,
				"varNames":selNames
			}),
			dataType: 'json',
			success: function (json_data) {
			//	console.log(JSON.parse(json_data.d))
				for (var i = 0; i < g_chart_series['series'].length; i++) {
					var __data = g_chart_series['series'][i].data
					var __name = g_chart_series['series'][i].name
					__sim_gen_hist_data(JSON.parse(json_data.d),__data,__name)
				}
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function chart_get_and_add_new_data()
{
	if (g_chart_series == null) {
		//alert('null g_chart_series')
		$.messager.alert("Tips", "null g_chart_series.", "info");
		clearInterval(g_dyn_chart_update_timer)
		return
	}
	t_now = new Date(+t_now + ONE_SECOND)
	for (var i = 0; i < g_chart_series['series'].length; i++) {
		if (ams_is_sim_mode()) {
			var __data = g_chart_series['series'][i].data
			__data.shift()
			var tmp;
			tmp = __sim_randomData(__data[__data.length-1].value[1])
			if (tmp != null)
			{
				__data.push(tmp)
			}
		}
		else{
			__get_read_time_data(g_chart_series['series'][i].name)
		}
	}

	g_dyn_chart.setOption(g_chart_series)
}

function __get_read_time_data(name){
	var tagNames = new Array();
	tagNames.push(name);

	$.ajax({
	type: 'POST',
	contentType: 'application/json',
	url: getWebServiceUrl("getEquipRTDatas"),
	data:JSON.stringify({
		"eqName":eqn,
		"varNames":tagNames
	}),
	dataType: 'json',
	success: function (json_data) {
		var obj = JSON.parse(json_data.d)
		var tagValue = Number(obj.series[0].data[0].value)
		var tagTime = String(obj.series[0].data[0].time)
		//t_now = (new Date(String(obj.series[0].data[0].time)))
		//console.log(JSON.parse(json_data.d))
		if( tagValue == null)
			alert(tagValue);
		for (var i = 0; i < g_chart_series['series'].length; i++) {
			if (g_chart_series['series'][i].name == obj.series[0].name)
			{
				var __data = g_chart_series['series'][i].data;
				__data.shift();
				var tmp = {name: tagTime,value: [tagTime, tagValue]};
				__data.push(tmp);
				break;
			}
		}
	},
	error: function (response) {
		//alert(errorThrown.message);
		//alert('Error: ' + response.responseText)
		$.messager.alert("Error", "Error: " + response.responseText, "error");
	}
 });
}

function __sim_randomData(base_v) {

//	if (ams_is_sim_mode()) {
		base_v = base_v + Math.random() * 21 - 10;
	    return {
	        name: t_now.toString(),
	        value: [
				[t_now.getFullYear(), t_now.getMonth() + 1, t_now.getDate()].join('/')
					+ ' ' + 
					[pad0(t_now.getHours(),2), pad0(t_now.getMinutes(),2), pad0(t_now.getSeconds(), 2)].join(':'),
	            Math.round(base_v)
	        ]
	    }
//	}else{
//	}
}

function __sim_gen_hist_data(json_data,data_array,name)
{
	if (ams_is_sim_mode()) {
		t_now = new Date(+t_now - ONE_SECOND*PT_COUNT)

		for (var i = 0; i < PT_COUNT; i++) {
			t_now = new Date(+t_now + ONE_SECOND)
			rnd_value = rnd_value + Math.random() * 21 - 10
			var tmp = {
					value: [
						datetime_format(t_now, 'yyyy/MM/dd hh:mm:ss'),
						Math.round(rnd_value)
						]
				}
			data_array.push(tmp)
		}
	}else{
		//debugger
		for(var i=0;i<json_data.series.length;i++){
			if(json_data.series[i].name==name){
				for(var j=0;j<json_data.series[i].data.length;j++){
					//alert(json_data.series[i].data[j].time + ":" + json_data.series[i].data[j].value)
					var tmp = {
						name: json_data.series[i].data[j].time,
						value: [
							json_data.series[i].data[j].time,
							json_data.series[i].data[j].value
						]
					}
					data_array.push(tmp)
				}
			}
		}
	}
}

</script>

</html>
